/**
 * 
 */
package com.ztesoft.web.baseconfig.service.impl;

import java.math.*;
import java.util.*;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ztesoft.core.common.Page;
import com.ztesoft.core.convert.IArgConversionService;
import com.ztesoft.core.idproduce.ISequenceGenerator;
import com.ztesoft.framework.exception.BaseAppException;
import com.ztesoft.framework.log.ZTEsoftLogManager;
import com.ztesoft.framework.util.Utils;
import com.ztesoft.web.baseconfig.db.arg.DmStrategyArg;
import com.ztesoft.web.baseconfig.db.arg.SubTableDefineArg;
import com.ztesoft.web.baseconfig.db.arg.DmStrategyArg.DmStrategyCriteria;
import com.ztesoft.web.baseconfig.db.arg.SubTableDefineArg.SubTableDefineCriteria;
import com.ztesoft.web.baseconfig.db.dao.SubTableDefineDao;
import com.ztesoft.web.baseconfig.db.po.DmStrategyPO;
import com.ztesoft.web.baseconfig.db.po.SubTableDefinePO;
import com.ztesoft.web.baseconfig.db.po.TableNamePO;
import com.ztesoft.web.baseconfig.service.ISubTableDefineService;
import com.ztesoft.web.common.DMSConstant.Status;

/**
 * <Description> <br>
 * 
 * @author codeCreater<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2014年11月11日 <br>
 * @since V1.0<br>
 * @see com.ztesoft.web.baseconfig.service.impl <br>
 */

@Service("subTableDefineService")
public class SubTableDefineServiceImpl implements ISubTableDefineService {

	private static final ZTEsoftLogManager logger = ZTEsoftLogManager.getLogger(SubTableDefineServiceImpl.class);

	@Autowired
	private SubTableDefineDao subTableDefineDao;

	/**
	 * 查询条件转换成Arg类的服务接口
	 */
	@Resource(name = "defaultArgConversionService")
	private IArgConversionService argConversionService;

	/**
	 * 主键生成器
	 */
	@Resource(name = "sequenceProcGenerator")
	private ISequenceGenerator sequenceGenerator;

	@Override
	public SubTableDefinePO selectByPrimaryKey(Integer key) throws BaseAppException {
		// ///////
		// TODO 根据业务场景，设置查询条件、数据校验等

		// ///////
		return subTableDefineDao.selectByPrimaryKey(key);
	}

	@Override
	public List<SubTableDefinePO> selectByArg(SubTableDefinePO record) throws BaseAppException {
		logger.debug("selectByArg begin...record={0}", record);

		// 第一种方式：自己创建arg，自行设置查询条件及操作符
		// SubTableDefineArg arg = new SubTableDefineArg();
		// SubTableDefineCriteria criteria = arg.createCriteria();

		// 第二种方式：利用arg转换服务，转换出arg，带上查询条件及操作符，
		// 转换后，还可以自行对arg进行设置修改
		SubTableDefineArg arg = argConversionService.invokeArg(SubTableDefineArg.class, record);

		// ///////
		// TODO 根据业务场景，设置查询条件，示例
		// if (Utils.notEmpty(record.getUserName())) {
		// criteria.andUserNameLike(record.getUserName());
		// }
		// ///////

		return subTableDefineDao.selectByArg(arg);
	}

	@Override
	public List<SubTableDefinePO> selectBySourceDataId(SubTableDefinePO record) throws BaseAppException {
		logger.debug("selectByArg begin...record={0}", record);
		return subTableDefineDao.selectBySourceDataId(record);
	}

	@Override
	public Page<SubTableDefinePO> selectByArgAndPage(SubTableDefinePO record, Page<SubTableDefinePO> resultPage)
			throws BaseAppException {
		logger.debug("selectByArgAndPage begin...record={0}", record);

		// 第一种方式：自己创建arg，自行设置查询条件及操作符
		// SubTableDefineArg arg = new SubTableDefineArg();
		// //TODO 根据业务场景，设置查询条件，示例
		// SubTableDefineCriteria criteria = arg.createCriteria();
		// if (Utils.notEmpty(record.getUserName())) {
		// criteria.andUserNameLike(record.getUserName());
		// }

		// 第二种方式：利用arg转换服务，转换出arg，带上查询条件及操作符，
		// 转换后，还可以自行对arg进行设置修改
		SubTableDefineArg arg = argConversionService.invokeArg(SubTableDefineArg.class, record);

		resultPage = subTableDefineDao.selectByArgAndPage(arg, resultPage);

		return resultPage;
	}

	@Override
	public SubTableDefinePO add(SubTableDefinePO record) throws BaseAppException {
		logger.debug("add begin...record={0}", record);
		/*
		 * 替换，数据库必填，前台空值，的字段的值 所有非空字段： 不需要替换： 需要替换：
		 */
		// if (Utils.isEmpty(record.getPlanName())) {
		// record.setPlanName(DMSConstant.DRAFT_STRING_REPLACE);
		// }
		subTableDefineDao.insertSelective(record);
		return record;
	}

	@Override
	public int addForDraft(SubTableDefinePO record) throws BaseAppException {
		logger.debug("add begin...record={0}", record);

		return subTableDefineDao.insertSelective(record);
	}

	@Override
	public int update(SubTableDefinePO record) throws BaseAppException {
		logger.debug("update begin...record={0}", record);

		// ///////
		// TODO 根据业务场景，进行重名校验、数据有效性校验、设置属性默认值等

		// ///////

		return subTableDefineDao.updateByPrimaryKeySelective(record);
	}

	@Override
	public int delete(SubTableDefinePO record) throws BaseAppException {
		logger.debug("delete begin...record={0}", record);
		// 获取序列号
		SubTableDefineArg arg_sub = new SubTableDefineArg();
		SubTableDefineCriteria criteria_sub = arg_sub.createCriteria();
		criteria_sub.andSourceDataIdEqualTo(record.getSourceDataId());
		criteria_sub.andStateNotEqualTo(Status.CANCELLED.toString());
		List<SubTableDefinePO> stdPOList_sub = subTableDefineDao.selectByArg(arg_sub);
		if (stdPOList_sub.size() != 0) {// 存在分表
			int seqNbr_sub = stdPOList_sub.get(0).getSeqNbr() + 1;
			// 作废该表下的分表定义信息
			subTableDefineDao.updateTo00X(record.getSourceDataId());
			// 逐个插入新的00X记录
			for (SubTableDefinePO stdPO : stdPOList_sub) {
				stdPO.setSeqNbr(seqNbr_sub);
				stdPO.setStaffId(record.getStaffId());
				stdPO.setStateDate(new Date());
				stdPO.setState(Status.CANCELLED.toString());
				subTableDefineDao.insertSelective(stdPO);
			}
		}
		return 1;
	}

	@Override
	public List<TableNamePO> selectBySourceDataIdForSubAndTgt(String tableName, SubTableDefinePO po)
			throws BaseAppException {
		List<TableNamePO> tnPOList = subTableDefineDao.selectBySourceDataIdForSubAndTgt(po);
		if (tnPOList.size() == 0) {
			TableNamePO tnPO = new TableNamePO();
			tnPO.setType("table");
			tnPO.setValue(tableName);
			tnPOList.add(tnPO);
			return tnPOList;
		}
		tnPOList.get(0).setType("table");
		for (int i = 1; i < tnPOList.size(); i++) {
			if (tnPOList.get(i).getTypeDb() == 0) {// 固定
				tnPOList.get(i).setType("val");
			} else {
				if (tnPOList.get(i).getValue().equals(tnPOList.get(i).getSubRefCol())) {// 可变参数
					tnPOList.get(i).setVariableValue(0);
				} else {
					tnPOList.get(i).setVariableValue(Integer.parseInt(tnPOList.get(i).getValue()));
				}
				tnPOList.get(i).setType("variable");
				tnPOList.get(i).setValue("可变参数");
			}
		}
		return tnPOList;
	}

	@Override
	public List<TableNamePO> selectBySourceDataIdForSrc(String tableName, SubTableDefinePO po) throws BaseAppException {
		List<TableNamePO> tnPOList = subTableDefineDao.selectBySourceDataIdForSrc(po);
		if (tnPOList.size() == 0) {
			TableNamePO tnPO = new TableNamePO();
			tnPO.setType("table");
			tnPO.setValue(tableName);
			tnPOList.add(tnPO);
			return tnPOList;
		}
		tnPOList.get(0).setType("table");
		for (int i = 1; i < tnPOList.size(); i++) {
			if (tnPOList.get(i).getTypeDb() == 0) {// 固定
				tnPOList.get(i).setType("val");
			} else {
				if ("2".equals(tnPOList.get(i).getValue())) {// 时间（年月）
					tnPOList.get(i).setType("timer");
					tnPOList.get(i).setTimerValue(tnPOList.get(i).getValue());
					tnPOList.get(i).setValue(
							"2," + tnPOList.get(i).getUpperOffset() + "," + tnPOList.get(i).getLowerOffset());
					// tnPOList.get(i).setValue("时间变量");
				} else if ("3".equals(tnPOList.get(i).getValue())) {// 时间（年月日）
					tnPOList.get(i).setType("timer");
					tnPOList.get(i).setTimerValue(tnPOList.get(i).getValue());
					tnPOList.get(i).setValue(
							"3," + tnPOList.get(i).getUpperOffset() + "," + tnPOList.get(i).getLowerOffset());
					// tnPOList.get(i).setValue("时间变量");
				} else if ("4".equals(tnPOList.get(i).getValue())) {// 账期
					tnPOList.get(i).setType("4");
					tnPOList.get(i).setValue(tnPOList.get(i).getUpperOffset() + "," + tnPOList.get(i).getLowerOffset());
					// tnPOList.get(i).setValue("账期");
				} else {// 其他
					tnPOList.get(i).setType("list");
				}
			}
		}
		return tnPOList;
	}

}
